package model

import (
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
)

// ServiceConfig systemd服务配置
const (
	ServiceName        = "ips"
	ServiceDescription = "IP地址查询服务"
	ServiceUser        = "www-data"
	ServiceGroup       = "www-data"
	ServiceWorkingDir  = "/opt/ips"
	ServiceExecStart   = "/opt/ips/ips"
	ServiceRestart     = "always"
	ServiceRestartSec  = "10"
)

// ServiceManager systemd服务管理器
type ServiceManager struct {
	ServiceFile string
	BinaryPath  string
}

// NewServiceManager 创建服务管理器
func NewServiceManager(binaryPath string) *ServiceManager {
	return &ServiceManager{
		ServiceFile: "/etc/systemd/system/ips.service",
		BinaryPath:  binaryPath,
	}
}

// InstallService 安装systemd服务
func (sm *ServiceManager) InstallService() error {
	if os.Geteuid() != 0 {
		return fmt.Errorf("需要root权限来安装systemd服务")
	}
	if _, err := os.Stat(sm.BinaryPath); os.IsNotExist(err) {
		return fmt.Errorf("二进制文件不存在: %s", sm.BinaryPath)
	}
	
	// 创建目录并复制文件
	if err := os.MkdirAll(ServiceWorkingDir, 0755); err != nil {
		return fmt.Errorf("创建服务目录失败: %v", err)
	}
	destBinary := filepath.Join(ServiceWorkingDir, "ips")
	if err := copyFile(sm.BinaryPath, destBinary); err != nil {
		return fmt.Errorf("复制二进制文件失败: %v", err)
	}
	if err := os.Chmod(destBinary, 0755); err != nil {
		return fmt.Errorf("设置文件权限失败: %v", err)
	}

	// 创建服务文件
	serviceContent := sm.generateServiceFile()
	if err := os.WriteFile(sm.ServiceFile, []byte(serviceContent), 0644); err != nil {
		return fmt.Errorf("创建服务文件失败: %v", err)
	}

	// 启用服务
	if err := exec.Command("systemctl", "daemon-reload").Run(); err != nil {
		return fmt.Errorf("重新加载systemd配置失败: %v", err)
	}
	if err := exec.Command("systemctl", "enable", "ips").Run(); err != nil {
		return fmt.Errorf("启用服务开机启动失败: %v", err)
	}
	
	return nil
}

// copyFile 复制文件
func copyFile(src, dst string) error {
	sourceFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer sourceFile.Close()

	destFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer destFile.Close()

	_, err = io.Copy(destFile, sourceFile)
	return err
}

// UninstallService 卸载systemd服务
func (sm *ServiceManager) UninstallService() error {
	if os.Geteuid() != 0 {
		return fmt.Errorf("需要root权限来卸载systemd服务")
	}

	// 停止并禁用服务
	exec.Command("systemctl", "stop", "ips").Run()
	exec.Command("systemctl", "disable", "ips").Run()

	// 清理文件
	os.Remove(sm.ServiceFile)
	os.RemoveAll(ServiceWorkingDir)
	exec.Command("systemctl", "daemon-reload").Run()
	
	return nil
}

func (sm *ServiceManager) generateServiceFile() string {
	return fmt.Sprintf(`[Unit]
Description=%s
After=network.target
Wants=network.target

[Service]
Type=simple
User=%s
Group=%s
WorkingDirectory=%s
ExecStart=%s
Restart=%s
RestartSec=%s

# 安全设置
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=%s
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true

[Install]
WantedBy=multi-user.target
`, ServiceDescription, ServiceUser, ServiceGroup, ServiceWorkingDir, ServiceExecStart, ServiceRestart, ServiceRestartSec, ServiceWorkingDir)
}
